package threadlocal;

/**
 * @description: 分析threadLocal父子线程为什么不能传递
 * @author: kanggw
 * @date: 2024/2/22
 **/
public class ThreadLocalTest {

    public static void main(String[] args) throws InterruptedException {
        // 在main方法中定义一个threadLocal变量，然后建立一个子线程，在子线程中输出threadLocal变量的值
        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        ThreadLocal<String> threadLocal2 = new ThreadLocal<>();
        threadLocal.set("main");
        threadLocal2.set("main2");
        Thread thread = new Thread(() -> {

            System.out.println("out:" +threadLocal.get());
            threadLocal.set("child");
            System.out.println("out2:" +threadLocal.get());
        });
        thread.start();
        Thread.sleep(1000);
        System.out.println("main out" + threadLocal.get());
        System.out.println("main2 out" + threadLocal2.get());
        /**
         * 原因是每个线程都维护着一个ThreadLocalMap，当调用get方法时，会从自己的ThreadLocalMap中获取值，所以子线程是获取不到父线程ThreadLocalMap的值的
         */
    }


}
